<template>
  <view class="content" :class="['qn-page-' + theme]">
    <!-- 状态栏占位 -->
    <view class="u-status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 扫码弹窗 -->
    <u-popup
      v-model="showScanPopup"
      mode="bottom"
      height="95%"
      border-radius="20"
    >
      <view class="scanner-container">
        <view class="scanner-header">
          <view class="back-btn" @click="closeScanner">
            <u-icon name="arrow-left" size="32" color="#606266"></u-icon>
            <text class="back-text">返回</text>
          </view>
          <text class="title">扫码添加</text>
        </view>
        <view class="camera-wrapper">
          <camera
            v-if="showScanPopup"
            mode="scanCode"
            @scancode="onScanCode"
            class="scanner-camera"
          ></camera>
          <view class="scan-box"></view>
        </view>
        <!-- 扫码结果列表 -->
        <view class="scanned-items-container">
          <view v-if="scannedCartItems.length === 0" class="tip-text">
            请将镜头对准商品的条形码或二维码
          </view>
          <scroll-view v-else scroll-y class="items-scroll-view">
            <view
              v-for="item in scannedCartItems"
              :key="item.cartId"
              class="scanned-item"
            >
              <image :src="item.goodsImages" class="goods-image"></image>
              <view class="item-info">
                <view class="goods-title u-line-1">{{ item.goodsName }}</view>
                <view class="price-line">
                  <view class="price primary-color">
                    <!-- <text class="rmb-icon">¥</text> -->
                    <rich-text
                      :nodes="$_utils.splitPrice(item.price)"
                    ></rich-text>
                  </view>
                  <!-- Presale Number Box (no max) -->
                  <u-number-box
                    v-if="item.isDistribution === 5"
                    :value="item.buyNum"
                    :min="item.setNum"
                    @change="handleQuantityChange(item, $event)"
                  ></u-number-box>
                  <!-- Normal Sale Number Box (with max) -->
                  <u-number-box
                    v-else
                    :value="item.buyNum"
                    :min="item.setNum"
                    :max="Number(item.inventoryNum)"
                    @change="handleQuantityChange(item, $event)"
                  ></u-number-box>
                </view>
              </view>
              <u-icon
                name="trash"
                color="#fa3534"
                size="40"
                @click="handleRemoveItem(item)"
                class="remove-icon"
              ></u-icon>
            </view>
          </scroll-view>
        </view>
        <view class="scanner-footer">
          <u-button
            @click="goToCart"
            :disabled="scannedCartItems.length === 0"
            :custom-style="{ backgroundColor: primaryColor, color: '#fff' }"
          >
            去购物车结算 ({{ cartTotalCount }})
          </u-button>
        </view>
      </view>
    </u-popup>
    <!-- 加购弹窗 -->
    <AddCardModel
      @close="cardModelPopChange"
      :isShow="is_add_show"
      :goodsId="goods_id"
    />

    <view class="mp-search-box" :style="headerStyle">
      <view class="header-row">
        <view class="title-text">产品分类</view>
      </view>
      <view class="search-row">
		<view class="scan-btn" style="margin-right: 40rpx;" @click="openScanner">
          <u-icon name="scan" size="40"></u-icon>
          <!-- <view>扫码</view> -->
        </view>
        <view
          @click="goPage('/pagesT/search/index')"
          :style="{ backgroundColor: cateModel !== 4 ? '#ffffff' : '#f4f5f6' }"
          class="ser-input-view"
        >
          <text class="ibonfont ibonsousuo1"></text>
          <text>输入搜索商品发现更多好物…</text>
        </view>
        <view class="right-view">
          <!-- #ifdef MP-WEIXIN -->
          <button class="contact-btn" open-type="contact">
            <u-icon name="server-fill" color="#000000" size="32"></u-icon>
            <view>商城客服</view>
          </button>
          <!--  #endif -->
          <!-- #ifdef APP-PLUS || H5 -->
          <button class="contact-btn" @click="callphone">
            <u-icon name="server-fill" color="#000000" size="32"></u-icon>
            <view>客服</view>
          </button>
          <!--  #endif -->
        </view>
      </view>
    </view>
    <view class="cate-main" :style="mainStyle">
      <cateOne v-if="cateModel === 1"></cateOne>
      <CateTwo v-if="cateModel === 2"></CateTwo>
      <CateThree v-if="cateModel === 3"></CateThree>
      <CateFive v-if="cateModel === 5"></CateFive>
      <CateFour
        :selAddress="now_sel_address"
        v-if="cateModel === 4"
        :isLogin="isLogin"
      ></CateFour>
    </view>
    <!-- 底部tabbar -->
    <Tabbar v-model="current"></Tabbar>
  </view>
</template>

<script>
import cateOne from "./CateOne.vue";
import CateTwo from "./CateTwo.vue";
import CateThree from "./CateThree.vue";
import CateFour from "./CateFour.vue";
import CateFive from "./CateFive.vue";
import AddCardModel from "@/components/AddCardModel";

export default {
  components: {
    cateOne,
    CateTwo,
    CateThree,
    CateFour,
    CateFive,
    AddCardModel,
  },
  computed: {
    cartTotalCount() {
      return this.scannedCartItems.reduce(
        (total, item) => total + item.buyNum,
        0
      );
    },
    primaryColor() {
      return (
        (this.$store.state.theme && this.$store.state.theme.themeColor) ||
        "#FB5904"
      );
    },
    style() {
      const systemInfo = uni.getSystemInfoSync();
      return `top:${systemInfo.statusBarHeight + 44}px`;
    },
    enterprisemobile() {
      return this.$store.state.enterpriseInfo.mobile;
    },
    cateModel() {
      return this.$store.state.cateModel;
    },
    headerStyle() {
      return `top: ${this.statusBarHeight}px;`;
    },
    mainStyle() {
    //   return `padding-top: ${this.headerHeight}px;`;
	return ''
    },
  },
  onNavigationBarButtonTap() {
    this.goPage("/pagesT/search/index");
  },
  data() {
    const systemInfo = uni.getSystemInfoSync();
    return {
      statusBarHeight: systemInfo.statusBarHeight,
      headerHeight: systemInfo.statusBarHeight + 90, // 90px for the custom header
      current: 1,
      now_sel_address: {},
      isLogin: true,
      showScanPopup: false,
      scannedGoods: null,
      is_add_show: false,
      goods_id: 0,
      isScanning: false, // Add this line
      scannedCartItems: [], // 快捷购物车列表
      scannedSkuIds: null, // 记录本次扫码会话中添加的sku
      // Keep original data
      conptop: {
        // #ifdef H5
        paddingTop: "44px",
        // #endif
        // #ifdef MP-WEIXIN
        paddingTop: "124rpx",
        // #endif
      },
    };
  },
  onShow() {
    this.isLogin = this.$common.isLogin();
  },
  onLoad() {
    // #ifdef MP-WEIXIN
    // 小程序的原生菜单中显示分享按钮
    uni.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    // #endif
  },
  methods: {
    openScanner() {
      if (!this.$common.isLogin()) {
        this.$u.toast("请先登录");
        return;
      }
      this.scannedSkuIds = new Set();
      this.scannedCartItems = [];
      this.showScanPopup = true;
    },
    closeScanner() {
      this.scannedCartItems = [];
      this.scannedSkuIds = null;
      this.showScanPopup = false;
    },
    clearScanned() {
      this.scannedGoods = null;
      this.isScanning = false; // Add this line to allow scanning again
    },
    onScanCode(e) {
      if (this.isScanning) {
        return; // Prevent multiple scans
      }
      this.isScanning = true; // Lock scanning

      const code = e.detail.result;
      if (code) {
        this.$u.api
          .getGoodsByBarCode({
            barCode: code,
          })
          .then((res) => {
            if (!res.data || !res.data.detail) {
              this.$u.toast("未找到该商品");
              setTimeout(() => {
                this.isScanning = false;
              }, 2000); // 2秒冷却，防止重复扫无效码
              return;
            }
            const detail = res.data.detail;
            this.processScannedGoods(detail);
          })
          .catch(() => {
            this.$u.toast("扫码请求失败");
            this.isScanning = false;
          });
      } else {
        this.isScanning = false; // Unlock if no code is detected
      }
    },
    async processScannedGoods(goodsDetail) {
      console.log("--- Scanned Goods Detail ---", JSON.stringify(goodsDetail));
      if (
        goodsDetail.isDistribution === 4 &&
        goodsDetail.inventorTotal <= 0
      ) {
        this.$u.toast("当前商品补货中");
        setTimeout(() => {
          this.isScanning = false;
        }, 2000);
        return;
      }

      let skuToAdd = null;
      if (goodsDetail.specMultiple && goodsDetail.specMultiple.length > 0) {
        // 优先找默认规格
        skuToAdd = goodsDetail.specMultiple.find(
          (item) => item.isDefault === 5 && item.isSale !== 4
        );
        // 如果没有默认，找第一个可售的
        if (!skuToAdd) {
          skuToAdd = goodsDetail.specMultiple.find(
            (item) => item.isSale !== 4
          );
        }
      }

      if (!skuToAdd) {
        this.$u.toast("该商品暂无可用规格");
        setTimeout(() => {
          this.isScanning = false;
        }, 2000);
        return;
      }
      
      // Add SKU-specific inventory check
      if (goodsDetail.isDistribution === 4 && skuToAdd.inventory <= 0) {
        this.$u.toast("该商品规格暂无库存");
        setTimeout(() => {
            this.isScanning = false;
        }, 2000);
        return;
      }

      if (this.scannedSkuIds.has(skuToAdd.id)) {
        this.$u.toast("商品已在列表中，请直接修改数量");
        setTimeout(() => {
          this.isScanning = false;
        }, 2000);
        return;
      }

      const goodsData = [
        {
          goodsBasicId: goodsDetail.basicGoodsId,
          goodsId: goodsDetail.id,
          buyNum: skuToAdd.setNum || 1,
          shopId: goodsDetail.shopId,
          source: this.$common.source(),
          skuId: skuToAdd.id,
        },
      ];
      try {
        await this.$u.api.addCart({
          goodsData,
        });

        this.$u.toast("添加成功");
        this.scannedSkuIds.add(skuToAdd.id);
        await this.refreshScannedItemsList();
      } catch (error) {
        console.error("处理扫描商品出错:", error);
        this.$u.toast("操作失败，请重试");
      } finally {
        setTimeout(() => {
          this.isScanning = false;
        }, 2000); // 2秒后允许再次扫描
      }
    },
    async refreshScannedItemsList() {
      const { data } = await this.$u.api.getCartByUserCenterId();
      if (!data || !data.goodsData) {
        this.scannedCartItems = [];
        return;
      }
      const flatCart = data.goodsData.flatMap((shop) => shop.shopGoodsData);
      this.scannedCartItems = flatCart.filter((item) =>
        this.scannedSkuIds.has(item.skuId)
      );
    },
    async handleQuantityChange(item, event) {
      console.log("--- handleQuantityChange ---");
      console.log("Item before:", JSON.stringify(item));
      console.log("Event payload:", JSON.stringify(event));
      // Robustly get the new value, whether the event is the value itself or an object containing the value.
      const newBuyNum = (event && typeof event === 'object' && event.value !== undefined) ? event.value : event;

      // It's possible for the event to be invalid or for the value to be unchanged.
      if (newBuyNum === undefined || newBuyNum === null || newBuyNum === item.buyNum) {
          return;
      }
      console.log("New buyNum:", newBuyNum);

      const originalBuyNum = item.buyNum;

      // Optimistic update: Immediately update the local data to prevent flickering.
      item.buyNum = newBuyNum;

      try {
        // Then, send the update to the server.
        await this.$u.api.updateBuyNum(item.cartId, { buyNum: newBuyNum });
        // If successful, do nothing as the UI is already updated.
      } catch (error) {
        // If the API call fails, revert the change and notify the user.
        this.$u.toast("数量更新失败");
        item.buyNum = originalBuyNum; // Rollback
      }
    },
    async handleRemoveItem(item) {
      uni.showModal({
        title: "提示",
        content: "确定要移除此商品吗?",
        success: async (res) => {
          if (res.confirm) {
            try {
              await this.$u.api.delCart({ cartId: [item.cartId] });
              this.$u.toast("已移除");
              this.scannedSkuIds.delete(item.skuId);
              this.scannedCartItems = this.scannedCartItems.filter(
                (i) => i.cartId !== item.cartId
              );
            } catch (error) {
              this.$u.toast("移除失败");
            }
          }
        },
      });
    },
    goToCart() {
      this.closeScanner();
      uni.switchTab({
        url: "/pages/cart/cart",
      });
    },
    confirmAddToCart() {
      if (!this.scannedGoods) return;
      this.goods_id = this.scannedGoods.id;
      this.is_add_show = true;
    },
    cardModelPopChange(obj) {
      this.is_add_show = false;
      this.scannedGoods = null;
      this.isScanning = false; // Add this line to allow scanning again
    },
    callphone() {
      uni.makePhoneCall({
        phoneNumber: this.enterprisemobile,
      });
    },
  },
  // 发送给朋友
  onShareAppMessage() {
    return {
      title: this.$store.state.baseSet.shop,
      path:
        "/pages/index/index?businessmanId=" +
        (this.$store.state.userStatus.id || ""),
      success: (res) => {
        console.log(res);
      },
    };
  },
  // #ifdef MP-WEIXIN
  // 分享到朋友圈
  onShareTimeline(obj) {},
  // 收藏小程序
  onAddToFavorites() {},
  // #endif
};
</script>

<style lang="scss">
.u-status-bar {
  width: 100%;
}
.header-row {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 44px;
  padding: 0 50rpx;

  .scan-btn {
    font-size: 20rpx;
    color: #2a2a2a;
    line-height: 1.3;
    text-align: center;
  }

  .title-text {
    font-size: 32rpx;
    font-weight: bold;
  }

  .placeholder {
    width: 80rpx; // Approximately the width of the scan button
  }
}

.search-row {
  display: flex;
  align-items: center;
  padding: 0 30rpx 24rpx;
}

.scanned-items-container {
  flex: 7;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  margin-top: -20rpx;
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  padding: 20rpx 0;
  overflow: hidden;
  .items-scroll-view {
    height: 100%;
    // padding: 0 30rpx;
  }
  .scanned-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border-bottom: 1px solid #f0f0f0;
    &:last-child {
      border-bottom: none;
    }
    .goods-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
      flex-shrink: 0;
    }
    .item-info {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 120rpx;
      width: 50%;
      overflow: hidden;
      min-width: 0; /* Prevents flex item from overflowing when content is too long */
      .goods-title {
        font-size: 28rpx;
        color: #333;
      }
      .price-line {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .price {
          font-size: 32rpx;
          font-weight: bold;
          .rmb-icon {
            font-size: 24rpx;
          }
        }
      }
    }
    .remove-icon {
      margin-left: 10rpx;
      padding: 10rpx;
    }
  }
}

.scanner-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  .scanner-header {
    display: flex;
    align-items: center;
    padding: 20rpx;
    position: relative;
    justify-content: center;
    border-bottom: 1px solid #f5f5f5;
    background-color: #fff;

    .back-btn {
      position: absolute;
      left: 10rpx;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      padding: 15rpx;
      color: #606266;
      z-index: 10;
    }

    .back-text {
      font-size: 28rpx;
      margin-left: 4rpx;
    }

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .camera-wrapper {
    flex: 3;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;

    .scanner-camera {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
    }

    .scan-box {
      width: 60vw;
      height: 60vw;
      max-width: 250px;
      max-height: 250px;
      border: 2px solid rgba(255, 255, 255, 0.8);
      border-radius: 12rpx;
      position: relative;
      box-shadow: 0 0 0 2000px rgba(0, 0, 0, 0.5);

      &::after {
        content: '';
        position: absolute;
        left: 5%;
        top: 0;
        width: 90%;
        height: 3px;
        background: linear-gradient(
          to right,
          transparent,
          #fb5904,
          transparent
        );
        animation: scan-animation 2s infinite linear;
      }
    }
  }

  @keyframes scan-animation {
    0% {
      top: 0;
    }
    100% {
      top: 98%;
    }
  }

  .scanner-footer {
    padding: 20rpx 40rpx 40rpx;
    display: flex;
    justify-content: center;
    background-color: #fff;
    border-top: 1px solid #f5f5f5;
    .u-button {
      width: 90%;
      height: 80rpx;
    }
  }
}

.content {
  height: 100vh;
  background-color: #fff;
}

.cate-main {
  /*
  position: fixed;
  left: 0;
  width: 100%;
  */
  height: calc(100vh - 250px); /* 50px for tabbar */
//   overflow-y: auto;
}

.mp-search-box {
//   position: fixed;
  left: 0;
  z-index: 999;
  width: 100%;

  .ser-input-view {
    flex: 1;
    height: 64rpx;
    background-color: #ffffff;
    border-radius: 64upx;
    line-height: 64upx;
    font-size: 24upx;
    color: #9fa8bd;
    font-weight: 400;

    .ibonfont {
      margin: 0 18rpx;
      display: inline-block;
      vertical-align: middle;
      font-size: 38rpx;
    }
  }

  .right-view {
    position: static;
    transform: none;
    margin-left: 20rpx;

    .contact-btn {
      background-color: transparent;
      font-size: 18rpx;
      font-weight: 400;
      color: #2a2a2a;
      line-height: 25rpx;
      text-align: center;
      padding: 0;

      &::after {
        border: 0 none;
      }
    }
  }
}
</style>
